package com.zsh.admin.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * @author zsh
 * @Description 测试文件上传
 * @create 2022-02-26 16:26
 */
@Controller
@Slf4j
public class FormTestController {

    @GetMapping("/form_layouts")
    public String form_layouts(){
        return "form/form_layouts";
    }

    /**
     * MultipartFile 自动封装文件
     * @param email
     * @param username
     * @param headerImg
     * @param photos
     * @return
     */
    @PostMapping("/upload")
    public String upload(@RequestParam("email") String email,
                         @RequestParam("username") String username,
                         @RequestPart("headerImg") MultipartFile headerImg,
                         @RequestPart("photos")MultipartFile[] photos) throws IOException {

        log.info("上传信息：email={}, username={}, headerImg={}, photos={}",
                email,username,headerImg.getSize(),photos.length);

        if (!headerImg.isEmpty()){
            //保存到文件服务器
            String filename = headerImg.getOriginalFilename();
            headerImg.transferTo(new File("E:\\ex\\"+filename));
        }

        if (photos.length > 0){
            for(MultipartFile photo:photos){
                if (!photo.isEmpty()){
                    String filename = photo.getOriginalFilename();
                    photo.transferTo(new File("E:\\ex\\"+filename));
                }
            }
        }


        return "main";
    }
}
